﻿using Jay.Sc2.Bof.Lib.State;

namespace Jay.Sc2.Bof.Lib.Action.Protoss
{
	public abstract class ActionProduceFromProbe : ActionProduceProtoss
	{
		public ActionProduceFromProbe(int buildTime, int minerals, int gas) : base(buildTime, minerals, gas, 0) { }

		public override int AvailableProducer(IBuildOrder bo)
		{
			ProtossState state = bo.State as ProtossState;
			return state.WorkersOnMinerals + state.WorkersOnGas;
		}

		public abstract ProtossState.ProtossBuilding GetBuilding(ProtossState state);
		public abstract string EventName { get; }

		public override void Execute(IBuildOrder bo)
		{
			ProtossState state = bo.State as ProtossState;
			if (state.WorkersOnMinerals > 0)
			{
				base.Execute(bo);
				OnProductionStart(bo);
				bo.AddAction(state.Time + BuildTime, new ActionGeneric(EventName, delegate(IBuildOrder ibo)
				{
					OnProductionFinished(ibo);
				}));
			}
			else if (state.WorkersOnGas > 0)
			{
				base.Execute(bo);
				OnProductionStart(bo);
				bo.AddAction(state.Time + BuildTime, new ActionGeneric(EventName, delegate(IBuildOrder ibo)
				{
					OnProductionFinished(ibo);
				}));
			}
			else throw new InvalidActionException();
		}

		public virtual void OnProductionFinished(IBuildOrder bo)
		{
			ProtossState.ProtossBuilding building = GetBuilding(bo.State as ProtossState);
			if (building != null)
				building.Built();
		}
		public virtual void OnProductionStart(IBuildOrder bo)
		{
			ProtossState.ProtossBuilding building = GetBuilding(bo.State as ProtossState);
			if (building != null)
				building.Building++;
		}
	}
}
